
import random
import re

from datetime import datetime
from flask import request, current_app, make_response, jsonify, session, render_template
from flask import make_response
from info import redis_store, constants, db
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.modules.index import index_blu
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET

from . import passpotr_blu

@passpotr_blu.route('/logout')
def logout():
    """
    退出登录
    :return:
    """
    # pop是移除session中的数据(dict)
    # pop 会有一个返回值，如果要移除的key不存在，就返回None
    session.pop('user_id', None)
    session.pop('mobile', None)
    session.pop('nick_name', None)

    return jsonify(errno=RET.OK, errmsg="退出成功"





@index_blu.route('/')
def index():
    # return render_template("new/index.html")
    user_id = session.get("user_id",None)
    user=None
    if user_id:
        try:
            user= User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    data = {
        "user":user.to_dict()if user else None
    }
    return render_template("new/index.html",data=data)




def login():
    """
        登录
        1. 获取参数
        2. 校验参数
        3. 校验密码是否正确
        4. 保存用户的登录状态
        5. 响应
        :return:
        """
    params_dict = request.json
    mobile = params_dict.get("mobile")
    passport = params_dict.get("passport")

    if not all([mobile,passport]):
        return jsonify(errno=RET.PARAMERR,errmsg="can shu cuowu")

    if not re.match('1[35678]\\d{9}', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式不正确")

    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
        # 判断用户是否存在
    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

        # 校验登录的密码和当前用户的密码是否一致
    if not user.check_password(passport):
        return jsonify(errno=RET.PWDERR, errmsg="用户名或者密码错误")

        # 4. 保存用户的登录状态
    session["user_id"] = user.id
    session["mobile"] = user.mobile
    session["nick_name"] = user.nick_name

    # 5. 响应
    return jsonify(errno=RET.OK, errmsg="登录成功")







@passpotr_blu.route('/register',methods=['post'])
def register():
    param_dict = request.json
    mobile = param_dict.get('mobile')
    smscode= param_dict.get('smscode')
    password = param_dict.git('password')

    if not all ([mobile,smscode,password]):
        return jsonify(error=RET.PARAMERR,errmsg='canshu buzu ')

    if not re.match('1[345678]\\d{10}',mobile):
        return jsonify(error=RET.PARAMERR,errmsg='shoouji haoma buzhengque')

    try:
        real_sms_code=redis_store.get('SMS_'+mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR,errmsg='cha xun shi bai')

    if not real_sms_code:
        return jsonify(error=RET.NODATA,errmsg='yan zhen ma yiguoqi')

    if real_sms_code != smscode:
        return jsonify(error=RET.DBERR,errmsg='yan zhen ma shuru cuowu')



    user=User()
    user.mobile=mobile

    user.nick_name=mobile
    user.last_login=datetime.now()



    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR,errmsg="shu ju bao cun shi bai")

    session['user_id']=user.id
    session['mobile']=user.mobile
    session['nick_name'] = user.nick_name

    return jsonify(error=RET.OK,errmsg='cheng gong')




@passpotr_blu.route('/sms_code',methods=['post'])
def send_sms_code():
    """
       发送短信的逻辑
       1. 获取参数：手机号，图片验证码内容，图片验证码的编号 (随机值)
       2. 校验参数(参数是否符合规则，判断是否有值)
       3. 先从redis中取出真实的验证码内容
       4. 与用户的验证码内容进行对比，如果对比不一致，那么返回验证码输入错误
       5. 如果一致，生成验证码的内容(随机数据)
       6. 发送短信验证码
       7. 告知发送结果
       :return:
       """
    param_dict = request.json
    img_mobile =param_dict.get('mobile')
    img_code = param_dict.get('image_code')
    img_code_id = param_dict.get('image_code_id')
    print(258)

    if not all([img_mobile,img_code,img_code_id]):
        return jsonify(errno=RET.PARAMERR,errmsg='can shu you wu ')

    if not re.match('^1[345678][0-9]{9}$',img_mobile):
        return jsonify(errno=RET.DATAERR,errmsg='shoujihaoma cuowu ')

    try:
        real_image_code = redis_store.get("ImageCode_"+img_code_id)
        print(369)
        if real_image_code:
            real_image_code=real_image_code.decode()
            redis_store.delete("ImageCode_"+img_code)
    except Exception as e:
        current_app.logger.error(e)

        return jsonify(errno=RET.DBERR,ermsg='huoqu shibai')

    if not real_image_code:

        return jsonify(errno=RET.NODATA,errmsg='yin zheng guo qi')

    if img_code.upper() != real_image_code.upper():
        return jsonify(errno=RET.DATAERR,errmsg='yan zheng ma shu ru cuo wu')


    result = random.randint(0,999999)
    print(147)
    sms_code = '%06d'%result
    current_app.logger.debug("短信验证码的内容：%s" % sms_code)
    # if result !=0:
    #     result jsonify()
    sms_code = "%06d" % result
    current_app.logger.debug("短信验证码的内容：%s" % sms_code)
    result = CCP().send_template_sms(img_mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES / 60], "1")

    # if result != 0:
    #     # 发送短信失败
    #     return jsonify(errno=RET.THIRDERR, errmsg="发送短信失败")




    try:
        redis_store.set('SMS_'+img_mobile,sms_code,constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)


        return jsonify(errno=RET.DBERR,errmsg="bao cun shi bai")
    return jsonify(errno=RET.OK,errmsg='fa song cheng gong')


@passpotr_blu.route('/image_code')
def get_image_code():
    """
     生成图片验证码并返回
     1. 取到参数
     2. 判断参数是否有值
     3. 生成图片验证码
     4. 保存图片验证码文字内容到redis
     5. 返回验证码图片

     :return:
     """

    code_id = request.args.get('imageCodeId')

    name,text,image = captcha.generate_captcha()

    current_app.logger.debug('tu pian shi : %S'%text)

    try:
        redis_store.setex('ImageCode_'+code_id,constants.IMAGE_CODE_REDIS_EXPIRES,text)

    except Exception as e:
        current_app.logger.error(e)

        return make_response(jsonify(errno=RET.DATAERR,errmsg="bao cun shi bai"))

    resp = make_response(image)
    resp.headers['Content-Type'] = 'image/jpg'
    return resp